package com.czy.owner.ui.archive;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.adapter.DetectionResultAdapter;
import com.czy.owner.adapter.DetectionResultPointAdapter;
import com.czy.owner.api.MaintenanceDetectionApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.DetectionResult;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.work.WorkShowActivity;
import com.czy.owner.utils.PhoneUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.czy.owner.ui.work.WorkShowActivity.TRANSMISSION_WORK_EXTEND_KEY;
import static com.czy.owner.ui.work.WorkShowActivity.TRANSMISSION_WORK_TYPE_KEY;
import static com.czy.owner.ui.work.WorkShowActivity.WorkJumpType.DETECTION;

/**
 * Created by King on 2017-05-15
 * 保养检测结果
 */

public class DetectionResultActivity extends BaseActivity {
    @BindView(R.id.tv_car_brand)
    TextView tvBrand;
    @BindView(R.id.tv_car_mileage)
    TextView tvMileage;

    @BindView(R.id.rv_detection_result_point)
    RecyclerView rvPoint;
    @BindView(R.id.elv_detection_result)
    ExpandableListView elvResult;
    @BindView(R.id.btn_maintenance_monitor)
    Button btnMaintenanceMonitor;

    private CarInfo mCarInfo;
    private String mileage;
    private DetectionResult mDetectionResult;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_detection_result;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("保养检测");
        getSubTitle().setText("保养手册");

        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(this, "参数异常!");
            finish();
            return;
        }
        mileage = getIntent().getStringExtra("mileage");
        tvBrand.setText(mCarInfo.getChName());
        SpannableStringBuilder ssb = new SpannableStringBuilder(mileage + "km");
        ssb.setSpan(new AbsoluteSizeSpan(16, true), mileage.length(), (mileage + "km").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvMileage.setText(ssb);

        getSubTitle().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DetectionResultActivity.this, MaintenanceManualActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo), 0);
            }
        });
    }

    @Override
    protected void updateViews() {
        MaintenanceDetectionApi maintenanceDetectionApi = new MaintenanceDetectionApi(new HttpOnNextListener<DetectionResult>() {
            @Override
            public void onNext(DetectionResult o) {
                mDetectionResult = o;
                showPoint();
                showResult();
                btnMaintenanceMonitor.setEnabled(true);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                //Toast.makeText(DetectionResultActivity.this, e.getMessage()+"|King", Toast.LENGTH_SHORT).show();
            }
        },DetectionResultActivity.this);



        HashMap<String,Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(DetectionResultActivity.this).getSession());
        requestMap.put("carBrandId",mCarInfo.getCarBrandId());
        requestMap.put("mileage",mileage);

        maintenanceDetectionApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(maintenanceDetectionApi);

        btnMaintenanceMonitor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DetectionResultActivity.this, WorkShowActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo).putExtra(TRANSMISSION_WORK_TYPE_KEY,DETECTION).putExtra(TRANSMISSION_WORK_EXTEND_KEY,mDetectionResult), 0);
            }
        });
    }

    private void showPoint() {
        if(mDetectionResult == null ){
            return;
        }
        List<Long> pointData = new ArrayList<>();

        for(int i = 0; i < mDetectionResult.getTimeMileageList().size();i++){
            pointData.add(mDetectionResult.getTimeMileageList().get(i).getMileage());
        }

        Collections.sort(pointData, new Comparator<Long>() {
            @Override
            public int compare(Long o1, Long o2) {
                if (o1 < o2) {
                    return -1;
                } else if (o1 == o2) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        int index = 0;
        for (int i = 0; i < pointData.size(); i++) {
            if (pointData.get(i) >= Long.valueOf(mileage)) {
                mDetectionResult.setTimeMileageId(mDetectionResult.getTimeMileageList().get(i).getTimeMileageId());
                index = i;
                break;
            }
        }

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        DetectionResultPointAdapter pointAdapter = new DetectionResultPointAdapter(this, pointData);
        pointAdapter.setIndex(index);
        rvPoint.setLayoutManager(layoutManager);
        rvPoint.setAdapter(pointAdapter);
    }

    private void showResult() {
        if(mDetectionResult == null ){
            return;
        }


        DetectionResultAdapter resultAdapter = new DetectionResultAdapter(this, mDetectionResult.getModelsList());
        elvResult.setAdapter(resultAdapter);
        elvResult.setGroupIndicator(null);

        for (int i = 0; i < mDetectionResult.getModelsList().size(); i++) {
            elvResult.expandGroup(i);
        }
        elvResult.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }
    }
}
